<template>
  <!-- 分配权限的弹层 -->
  <el-dialog title="分配权限(一级为路由页面查看权限-二级为按钮操作权限)" :visible="showDialogAssign" @close="hClose">
    <el-tree
      ref="tree"
      node-key="id"
      default-expand-all
      :show-checkbox="true"
      :check-strictly="true"
      :data="permissionData"
      :props="{ label: 'name' }"
  />
  <el-button type="success" @click="hSave">确认</el-button>
  </el-dialog>
</template>
<script>
import { getPermissionList } from '@/api/permission'
import { arr2tree } from '@/utils/index'
import { getRoleDetail, assignPerm } from '@/api/role'
export default {
  name: 'AssignPermission',
  data() {
    return {
      permIds: [],
      permissionData: [] // 存储权限数据
    }
  },
  props: {
    showDialogAssign: {
      type: Boolean,
      default: false
    },
    roleId: {
      type: Number,
      default: 0
    }
  },
  created() {
    this.loadPermissionList()
  },
  methods: {
    async hSave() {
      const permIds = this.$refs.tree.getCheckedKeys()
      // console.log('当前选中的节点数组是', permIds)
      const res = await assignPerm({
        id: this.roleId,
        permIds
      })
      console.log('保存角色的权限点的结果是', res)

      // 提示
      this.$message.success('保存角色的权限成功')
      // 关闭弹层
      this.hClose()
    },
    async loadPermissionList() {
      // 发送请求, 获取权限列表
      const data = await getPermissionList()
      this.permissionData = arr2tree(data, 0)
    },
    hClose() {
      this.$emit('update:showDialogAssign', false)
    },

    async loadPermission() {
      const { permIds } = await getRoleDetail(this.roleId)
      this.permIds = permIds
      // 回填
      this.$refs.tree.setCheckedKeys(permIds)
    }
  }
}
</script>